from django.db import models
from django.contrib.auth.models import User

class EmergencyInfo(models.Model):
    family_member = models.OneToOneField('families.FamilyMember', on_delete=models.CASCADE)
    BLOOD_TYPE_CHOICES = [
        ('A', 'A'),
        ('B', 'B'),
        ('AB', 'AB'),
        ('O', 'O'),
        ('unknown', 'Unknown'),
    ]
    blood_type = models.CharField(max_length=10, choices=BLOOD_TYPE_CHOICES, default='unknown')
    
    RH_FACTOR_CHOICES = [
        ('positive', 'Positive'),
        ('negative', 'Negative'),
        ('unknown', 'Unknown'),
    ]
    rh_factor = models.CharField(max_length=10, choices=RH_FACTOR_CHOICES, default='unknown')
    
    allergies = models.TextField(blank=True)
    chronic_diseases = models.TextField(blank=True)
    past_surgeries = models.TextField(blank=True)
    primary_doctor = models.CharField(max_length=100, blank=True)
    hospital_preference = models.CharField(max_length=200, blank=True)
    insurance_info = models.TextField(blank=True)
    emergency_contact_name = models.CharField(max_length=50, blank=True)
    emergency_contact_phone = models.CharField(max_length=20, blank=True)
    emergency_contact_relation = models.CharField(max_length=20, blank=True)
    qr_code_url = models.URLField(blank=True)
    last_reviewed_date = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # 运营监控字段 - 对应应急模式页紧急信息展示与一键呼救
    view_count = models.IntegerField(default=0, help_text="应急信息查看次数")
    qr_scan_count = models.IntegerField(default=0, help_text="二维码扫描次数")
    last_accessed_at = models.DateTimeField(null=True, blank=True, help_text="最后访问时间")

    def __str__(self):
        return f"Emergency Info for {self.family_member.user.username}"


class EmergencyEvent(models.Model):
    EVENT_TYPE_CHOICES = [
        ('info_view', 'Info View'),
        ('qr_shared', 'QR Shared'),
        ('contact_called', 'Contact Called'),
        ('emergency_alert', 'Emergency Alert'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    family_member = models.ForeignKey('families.FamilyMember', on_delete=models.CASCADE)
    event_type = models.CharField(max_length=20, choices=EVENT_TYPE_CHOICES)
    recipient_info = models.CharField(max_length=200, blank=True)
    location_data = models.JSONField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    # 运营监控字段 - 对应应急模式页一键呼救
    response_time = models.FloatField(null=True, blank=True, help_text="响应时间(秒)")
    success_status = models.BooleanField(default=True, help_text="是否成功处理")
    follow_up_required = models.BooleanField(default=False, help_text="是否需要后续跟进")

    def __str__(self):
        return f"{self.event_type} - {self.user.username}"